import { Injectable } from '@nestjs/common';
import { CreateSpiderDto } from './dto/create-spider.dto';
import { UpdateSpiderDto } from './dto/update-spider.dto';
import axios from 'axios';
import * as cheerio from 'cheerio';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class SpiderService {
  create(createSpiderDto: CreateSpiderDto) {
    return 'This action adds a new spider';
  }
  // 爬虫
  async findAll() {
    const urls: string[] = [];
    const cosplay = async () => {
      const body = await axios
        .get(
          'https://www.zhangxinxu.com/wordpress/2023/09/html-elementtiming-attribute/',
        )
        .then((res) => res.data)
        .catch((err) => err);
      const $ = cheerio.load(body);
      $('p img').each(function () {
        urls.push($(this).attr('src'));
      });
      console.log(urls);
    };
    await cosplay();
    this.writeFile(urls);
    return urls;
  }
  writeFile(urls: string[]) {
    urls.forEach(async (url: string) => {
      const buffer = await axios
        .get(url, { responseType: 'arraybuffer' })
        .then((res) => res.data);
      console.log(path.extname(url));
      const ws = fs.createWriteStream(
        path.join(__dirname, '../images/cos' + Date.now() + path.extname(url)),
      );
      ws.write(buffer);
    });
  }

  findOne(id: number) {
    return `This action returns a #${id} spider`;
  }

  update(id: number, updateSpiderDto: UpdateSpiderDto) {
    return `This action updates a #${id} spider`;
  }

  remove(id: number) {
    return `This action removes a #${id} spider`;
  }
}
